package org.mathcloud.math.io.mml.utilities;

import java.util.HashMap;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GenericXPathUtility
{
	/* search XPath expressing (arg1) in arg0
	 * */  
	public static boolean contains(Element arg0, String arg1) throws XPathExpressionException
	{		
		/* search XPath expressing (arg1) in arg0 
		 * returns true if matching found, false - otherwise
		 * */  
		XPathExpression expr = getXPathExpression(arg1);
		Object result = expr.evaluate(arg0, XPathConstants.NODE);
		Node node = (Node) result;
		if (node!=null)
			return true;
		else return false;
	}	

	public static NodeList findElements(Element arg0, String arg1) throws XPathExpressionException
	{
		/* search XPath expressing (arg1) in arg0
		 * returns all found Nodes if matching is found, null - otherwise
		 * */  
		XPathExpression expr = getXPathExpression(arg1);
		Object result = expr.evaluate(arg0, XPathConstants.NODESET);
		NodeList nodes = (NodeList) result;
		return nodes;
	}
	
	private static XPathExpression getXPathExpression(String arg0) 
		throws XPathExpressionException
	{
    XPathFactory factory = XPathFactory.newInstance();		
		XPath xpath = factory.newXPath();
		Map<String, String> mappings = new HashMap<String, String>();
    mappings.put(XMLConstants.XML_NS_PREFIX,XMLConstants.XML_NS_URI);
    mappings.put("mml","http://www.w3.org/1998/Math/MathML");
    NamespaceContext context = new NamespaceContextMap(mappings);			
		xpath.setNamespaceContext(context);						
		XPathExpression expr = xpath.compile(arg0);
		return expr;
	}
	
}
